package com.adv.io_3;

import java.io.*;

/**
 * 3：实现文件加密解密：加密规则是读出每一个字节，取反(~)后，写入 新文件，然后删除原文件，把新文件改成原文件同名的文件，
 * 解密规则类似。输入一个文件名，实现加密和解密功能
 * 
 * @author zhaoyang
 *
 */
public class IOwork3_Jiami {
//好像哪里不对 但又说不出来……
	public static void main(String[] args) throws IOException {
		// 读出取反
		File f1 = new File("/Users/zhaoyang/Desktop/dagang.txt");
		File f2 = new File("/Users/zhaoyang/Desktop/dagang2.txt");
		InputStream is = new BufferedInputStream(new FileInputStream(f1));
		byte[] c = new byte[(int) f1.length()];
		byte[] c2 = new byte[(int) f1.length()];
		int readChars = 0;
		while ((readChars = is.read(c)) != -1) {
			for (int i = 0; i < readChars; i++) {
				c2[i] = (byte) ~c[i];
			}
		}
		is.close();
		// 写出删除
		OutputStream op = new BufferedOutputStream(new FileOutputStream(f2));
		op.write(c2);
		op.close();
		f1.renameTo(f1);

		// 解密
		FileInputStream fs = new FileInputStream(f2);
		byte[] c3 = new byte[(int) f2.length()];
		byte i = 0;
		while ((c3[i] = (byte) fs.read()) != -1) {
			c3[i] = (byte) ~c3[i];
			i++;
		}
		File f3 = new File("/Users/zhaoyang/Desktop/dagang3.txt");
		OutputStream op3 = new FileOutputStream(f3);
		op3.write(c3);
		op3.close();

	}

}
